package com.bocai.kelalacar.ui.car.set.act;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.OnDismissListener;
import com.bocai.kelalacar.App;
import com.bocai.kelalacar.R;
import com.bocai.kelalacar.base.BaseActivity;
import com.bocai.kelalacar.bean.CarDriverBean;
import com.bocai.kelalacar.bean.UploadImgBean;
import com.bocai.kelalacar.ui.car.main.act.MainActivity;
import com.bocai.kelalacar.ui.car.set.ada.PhotoAda;
import com.bocai.kelalacar.ui.car.set.contract.AddCarContract;
import com.bocai.kelalacar.ui.car.set.module.AddCarModule;
import com.bocai.kelalacar.ui.car.set.presenter.AddCarPresenter;
import com.bocai.kelalacar.util.SP;
import com.bocai.kelalacar.widget.CarNumDialog;
import com.bocai.kelalacar.widget.MyGridView;
import com.bocai.kelalacar.widget.PhotoRemoveIndex;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPicker;

/**
 * Created by yuanfei on 2017/6/23.
 */

public class AddCarActivity extends BaseActivity implements AddCarContract.view,PhotoRemoveIndex{
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.right_btn)
    Button rightBtn;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.ed_license_plate)
    EditText edLicensePlate;
    @BindView(R.id.tv_car_age)
    TextView tvCarAge;
    @BindView(R.id.add_car_num)
    TextView addCarNum;
    @BindView(R.id.gv_photo)
    MyGridView gvPhoto;
    PhotoAda ada;
    ArrayList<String> photos = new ArrayList<>();
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.ll_right)
    LinearLayout llRight;
    CarNumDialog carNumDialog;
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @Inject
    AddCarPresenter presenter;
    CarDriverBean.ContentBean.CarListBean listBean;
    TimePickerView pickerView;

    @Override
    public int getLayoutId() {
        return R.layout.act_add_car;
    }

    @Override
    public void initPresenter() {
        App.get(this).getAppComponent().addSub(new AddCarModule(this)).inject(this);
    }

    @Override
    public void initView() {

        listBean = (CarDriverBean.ContentBean.CarListBean) getIntent().getSerializableExtra("data");

        initToolbar("车辆管理");
        initBack(imgBack,llBack);
        llRight.setVisibility(View.VISIBLE);
        tvRight.setText("保存");
        ada = new PhotoAda(this, photos);
        gvPhoto.setAdapter(ada);
        gvPhoto.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (photos.size() < 6) {
                    checkReadPermission();
                }
            }
        });
        presenter.optionalSeats();

        if (listBean != null&&listBean.getCarId()!=null){
            edLicensePlate.setText(listBean.getCarLicense());
            tvCarAge.setText(listBean.getCarAge()+"");
            addCarNum.setText(listBean.getSeats()+"");
            if (listBean.getCarImages()!=null&&listBean.getCarImages().size()!=0) {
                for (int i = 0; i < listBean.getCarImages().size(); i++) {
                    photos.add(listBean.getCarImages().get(i).getMediumThumbnail());
                }
                ada.setPhotos(photos);
                ada.setPhotoRemoveIndex(this);
            }
        }
        try {
            setDataView();
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }
    @OnClick({R.id.ll_right,R.id.add_car_num,R.id.tv_car_age})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.ll_right:
                if (TextUtils.isEmpty(edLicensePlate.getText().toString())){
                    showErrorTip("请输入车牌号");
                }else if (TextUtils.isEmpty(tvCarAge.getText().toString())){
                    showErrorTip("请输入车龄");
                }else if (TextUtils.isEmpty(addCarNum.getText().toString())){
                    showErrorTip("请选择车位数");
                }else if (photos == null||photos.size() == 0){
                    showErrorTip("请选择车辆图片");
                }else {
                    photos = ada.getPhotos();
                    if (listBean!=null&&listBean.getCarImages()!=null&&listBean.getCarImages().size()!=0){
                        for (int i = 0;i<listBean.getCarImages().size();i++){
                            photos.remove(0);
                        }
                    }
                    if (photos.size()==0){
                        if (listBean!=null&&listBean.getCarId()!=null&&!listBean.getCarId().equals("")){
                            StringBuilder stringBuilder = new StringBuilder();

                            if (listBean!=null&&listBean.getCarImages()!=null&&listBean.getCarImages().size()!=0){
                                for (int i = 0;i<listBean.getCarImages().size();i++){
                                    stringBuilder.append(listBean.getCarImages().get(i).getId()+",");
                                }
                            }
                            presenter.modifyCar(listBean.getCarId(), edLicensePlate.getText().toString(), tvCarAge.getText().toString(), addCarNum.getText().toString(), stringBuilder.toString());
                        }else {
                            presenter.addCar(SP.get(this, "id", "").toString(), edLicensePlate.getText().toString(), tvCarAge.getText().toString(), addCarNum.getText().toString(), "");
                        }
                    }else {
                        presenter.uploadImg(photos);
                    }

                }
                break;
            case R.id.add_car_num:
                carNumDialog.show();
                break;
            case R.id.tv_car_age:
                pickerView.show();
                break;

        }
    }

    public void doTakePhoto(){
        PhotoPicker.builder()
                .setPhotoCount(6 - photos.size())
                .setShowCamera(true)
                .setShowGif(false)
                .setPreviewEnabled(false)
                .start(AddCarActivity.this, PhotoPicker.REQUEST_CODE);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void checkReadPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //应用还未获取读取本地文件 的权限，询问是否允许
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 222);
        } else {
            doTakePhoto();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 111) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                checkReadPermission();
            } else {
                showErrorTip("权限被禁止，无法打开相机");
            }
        }else if (requestCode == 222){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                doTakePhoto();
            } else {
                showErrorTip("权限被禁止，无法打开相机");
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                photos = ada.getPhotos();
                List<String> list = new ArrayList<>();
                list = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                photos.addAll(list);
                ada.setPhotos(photos);
            }
        }
    }

    @Override
    public void addCarSuccess() {
        showErrorTip("添加车辆成功");
        finish();

    }

    public void setDataView() throws ParseException {
        // 指定一个日期
        pickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调

                Date date1 = new Date();

                if (date1.getYear() < (date.getYear())){
                    showErrorTip("选择时间晚于当前时间");
                }else {
                    tvCarAge.setText((1900 + date.getYear()) + "");
                }
            }
        })
                .setType(TimePickerView.Type.YEAR_MONTH_DAY)
                .build();
//        pickerView.show();
    }

    @Override
    public void uploadImgSuccess(UploadImgBean uploadImgBean) {
        StringBuilder stringBuilder = new StringBuilder();

        if (listBean!=null&&listBean.getCarImages()!=null&&listBean.getCarImages().size()!=0){
            for (int i = 0;i<listBean.getCarImages().size();i++){
                stringBuilder.append(listBean.getCarImages().get(i).getId()+",");
            }
        }

        for (int i = 0;i<uploadImgBean.getContent().size();i++){
            if (i == uploadImgBean.getContent().size() - 1){
                stringBuilder.append(uploadImgBean.getContent().get(i).getId());
            }else{
                stringBuilder.append(uploadImgBean.getContent().get(i).getId()+",");
            }
        }
        if (listBean!=null&&listBean.getCarId()!=null&&!listBean.getCarId().equals("")) {
            presenter.modifyCar(listBean.getCarId(), edLicensePlate.getText().toString(), tvCarAge.getText().toString(), addCarNum.getText().toString(), stringBuilder.toString());
        }else {
            presenter.addCar(SP.get(this, "id", "").toString(), edLicensePlate.getText().toString(), tvCarAge.getText().toString(), addCarNum.getText().toString(), stringBuilder.toString());
        }
    }

    @Override
    public void optionalSeatsList(final List<Integer> list) {
        carNumDialog = new CarNumDialog(this).builder().setList(list, new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                addCarNum.setText(list.get(position)+"");
                carNumDialog.dismiss();
            }
        });
    }




    @Override
    public void getCarList(CarDriverBean bean) {

    }

    @Override
    public void deleteCarSuccess(int index) {

    }

    @Override
    public void modifyCarSuccess() {
        showErrorTip("修改成功");
        finish();
    }

    @Override
    public void showLoading(String title) {
        startProgressDialog(title);
    }

    @Override
    public void stopLoading() {
        stopProgressDialog();
    }

    @Override
    public void showErrorTip(String msg) {
        showShortToast(msg);
        if (msg.equals("您的登录已失效，请重新登录")){
            startActivity(new Intent(this,MainActivity.class).putExtra("index",1));
            finish();
        }
    }

    @Override
    public void remove(int index) {
        if (index<listBean.getCarImages().size()) {
            listBean.getCarImages().remove(index);
        }
    }
}
